package config

import (
	"bytes"
	"os"
	"strings"
)

func checkFields(fields string) {
	ss := strings.Split(fields, ".")
	for _, s := range ss {
		if s == "" {
			panic("fields format error")
		}
		for _, c := range s {
			checkRune(c)
		}
	}
}

func checkRune(r rune) {
	if r >= '0' && r <= '9' {
		return
	}
	if r >= 'a' && r <= 'z' {
		return
	}
	if r >= 'A' && r <= 'Z' {
		return
	}
	if r == '-' || r == '_' {
		return
	}
	panic("field contains invalid rune")
}

func parseString(s string) string {
	if s == "" {
		return ""
	}
	if s[0] == '@' {
		b, _ := os.ReadFile(File(s[1:]))
		return string(b)
	}
	if s[0] != '"' {
		return s
	}
	if s[len(s)-1] != '"' {
		panic("string format error. unclosed quotes")
	}
	runes := bytes.Runes([]byte(s[1 : len(s)-1]))
	var buf bytes.Buffer
	for i := 0; i < len(runes); i++ {
		r := runes[i]
		if r == '"' {
			panic("string format error. unescaped quote")
		}
		if r == '\\' {
			i++
			if i >= len(runes)-1 {
				panic("string format error. end with \\")
			}
			switch runes[i] {
			case '\\':
				r = '\\'
			case 't':
				r = '\t'
			case 'r':
				r = '\r'
			case 'n':
				r = '\n'
			case '"':
				r = '"'
			default:
				panic("string format error. unknown escape \\" + string(runes[i]))
			}
		}
		buf.WriteRune(r)
	}
	return buf.String()
}
